// index.js
// 获取应用实例
const app = getApp()
const requests = require('../../config/request')
var util = require('./../../utils/util.js');
var api = require('./../../config/api.js');

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    schoolName: '',
    banners: [],
    autoplay: true,
    shopLists: [],
    menus: [],
    loadTimeInterval: true,
    page: 1,
    pageEnd: false,
    tableIndex: 0,
    commentList: [],
    commentPage: 1,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
    commentContent: '',
    commentPid: 0,
    showInput: false,
    commentEnd: false,
    isClearComment: false,
    isRefresh: false,
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }

    // var commentList = this.getCommentStorge()
    // this.setData({commentList: commentList})
    // if (commentList.length > 0){
    //   this.setData({isClearComment: true})
    // }

    let index = setInterval(() => {
      if (app.globalData.schoolInfo && app.globalData.schoolInfo.csName !== undefined) {
        clearInterval(index);
        this.setData({
          schoolName: app.globalData.schoolInfo.csName
        });

        // this.getCommentList(true)
        return;
      }
    }, 100)
    this.getBannerMenu();
    this.popularShopList();
  },

  onShow(){
    // if (app.globalData.userInfo){
    //   this.setData({isRefresh: true})
    //   this.getCommentList(false)
    // }
  },

  getCommentList: function(isShowLoading){
    var that = this;
    var postData = {};
    if (this.data.isRefresh){
      postData.page = 1;
      this.setData({isRefresh: false})
    }else{
      postData.page = this.data.commentPage;
    }
    
    postData.token = app.globalData.userInfo.token;
    console.log('page:' + this.data.commentPage)
    util.myRequest(api.GetCommentList, postData, function(data){
      if (data.data.length < 10){
        that.setData({commentEnd: true})
      }
      var newCommentList = [];
      var oldCommentList = that.data.commentList;
      for (var i=0;i<data.data.length;i++){
        var isRepeat = false
        for (var j=0;j<oldCommentList.length;j++){
          if (data.data[i].cId == oldCommentList[j].cId){
            isRepeat = true;
            oldCommentList[j] = data.data[i]
          }
        }
        if (!isRepeat){
          newCommentList.push(data.data[i])
        }
      }
      var nowList = oldCommentList.concat(newCommentList);
      if (postData.page == 1){
        nowList = newCommentList.concat(oldCommentList)
      }
      try {
        wx.setStorageSync('commentList', nowList)
      } catch (e) { }
      that.setData({commentList: nowList});
    }, false, false, isShowLoading);
  },

  getCommentStorge: function(){
    try {
      var commentList = wx.getStorageSync('commentList')
      return commentList
    } catch (e) {
      return []
    }
  },

  // 页面上拉触底事件的处理函数
  onReachBottom () {
    console.log("底部") // 滚动到页面执行 该 方法 
    wx.showToast({
      title: '加载中...',
      icon: 'loading',
      duration: 2000
    })
    /*
      这里执行你需要的请求数据追加到循环数组就好了
    */
  },
  atBottom: function(){
    var that = this;
    if (this.data.pageEnd){
      // wx.showToast({
      //   title: '没有更多了~',
      //   icon: 'none',
      //   duration: 2000
      // })
      return
    }
    if (this.data.loadTimeInterval){
      that.setData({loadTimeInterval: false});

      that.setData({page: that.data.page + 1})
      that.popularShopList();


      setTimeout(function(){
        that.setData({loadTimeInterval: true});
      }, 1500);
    }
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  getBannerMenu() {
    requests.homeMenuApi().then(({
      list,
      menu
    }) => {
      Array.isArray(list) && this.setData({
        banners: list
      })

      Array.isArray(menu) && this.setData({
        menus: menu
      })

    })
  },
  popularShopList() { // 热门店铺
    console.log('page:'+ this.data.page)
    requests.shopList({
      search_key: '',
      is_hot: '',
      cate_id2: '',
      page: this.data.page
    }).then(({
      list
    }) => {
      var newList = this.data.shopLists.concat(list);
      if (list.length < 20){
        console.log(list.length)
        this.setData({pageEnd: true});
      }
      Array.isArray(list) && this.setData({
        shopLists: newList
      })
    })
  },

  redirectToSearch() {
    wx.navigateTo({
      url: '../shop/list/index',
    })
  },

  redirectToShop(e) {
    let shopId = e.currentTarget.dataset.shopId;
    wx.navigateTo({
      url: '../shop/shop?shop_id=' + shopId,
    })
  },
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  
  clickMenu(e) {
    let category = e.currentTarget.dataset.category;
    if (!category) {
      return;
    }

    wx.navigateTo({
      url: '../shop/list/index?category=' + category,
    })
  },

  changeTab(e){
    let index = e.currentTarget.dataset.index;
    this.setData({tableIndex: index})
  },

  toPost(){
    wx.navigateTo({
      url: '../post/post'
    })
  },

  bindReplaceInput(e){
    this.setData({commentContent: e.detail.value});
  },

  showInput(e){
    this.setData({commentPid:  e.currentTarget.dataset.id})
    this.setData({showInput: true})
  },

  inputBlur(e){
    this.setData({showInput: false})
  },

  previewImg(e){
    for (var i=0;i<this.data.commentList.length;i++){
      if (this.data.commentList[i].cId == e.currentTarget.dataset.id){
        wx.previewImage({
          current: e.currentTarget.dataset.url, // 当前显示图片的http链接
          urls: this.data.commentList[i].picList // 需要预览的图片http链接列表
        })
      }
    }

    wx.previewImage({
      current: '', // 当前显示图片的http链接
      urls: [] // 需要预览的图片http链接列表
    })
  },

  sendComment(){
    var that = this;
    var postData = {};
    postData.token = app.globalData.userInfo.token;
    postData.cPid = this.data.commentPid;
    postData.cContent = this.data.commentContent;
    postData.pgId = 0
    util.myRequest(api.AddComment, postData, function(data){
      // that.getCommentList()
      var newCommentList = that.data.commentList;
      for (var i=0;i<newCommentList.length;i++){
        if (newCommentList[i].cId == that.data.commentPid){
            var replyInfo = {}
            replyInfo.cContent = that.data.commentContent
            replyInfo.userInfo = {uName: app.globalData.userInfo.uName}
            newCommentList[i].replyList.push(replyInfo)
            that.setData({commentList: newCommentList, commentContent: ''});
            console.log(newCommentList)
        }
      }
    });
  },

  atCommentBottom: function(){
    console.log('dddddddddddddd')
    console.log(this.data.commentEnd)
    console.log(this.data.loadTimeInterval)
    var that = this;
    if (this.data.commentEnd){
      return
    }
    if (this.data.loadTimeInterval){
      that.setData({loadTimeInterval: false});

      that.setData({commentPage: that.data.commentPage + 1})
      that.getCommentList(false)


      setTimeout(function(){
        that.setData({loadTimeInterval: true});
      }, 1500);
    }
  }
})